package com.oitsm.collection;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import bsh.Interpreter;

import com.oitsm.dispatcher.task.CollectTasker;
import com.oitsm.mo.entity.Monitor;
import com.oitsm.plugin.entity.Context;
import com.oitsm.plugin.entity.Response;
import com.oitsm.plugin.entity.ResponseItem;
import com.oitsm.plugin.entity.ResponseMeta;
/**
 * 监测器回调
 * @author Arab Runner
 * Jul 30, 2011 7:03:14 PM
 */
public class MonitorCallback implements CallbackAble {
	public static Logger logger = Logger.getLogger(MonitorCallback.class.getName());
	private Monitor m;
	public MonitorCallback(Monitor m){
		this.m = m;
	}

	public void call(Context ctx, Response res, CollectTasker task) {
		if(res.isSuccess()){
			
			// 先计算非抽象的
			for(ResponseMeta rm : task.getMeta().getResponses()){
				if(StringUtils.isNotEmpty(rm.getFormula()) && !rm.isAbstract()){
					calFormula(res.getItems(),rm);
				}
			}
//			
//			// 计算抽象的
			for(ResponseMeta rm : task.getMeta().getResponses()){
				if(rm.isAbstract()){
					calAbstract(res,rm);
				}
			}
			System.out.println(res.toString());
		}
		
		m.getSchedule().next(System.currentTimeMillis());
		m.setQueuedTime(-1);
	}
	
	public static void calAbstract(Response res,ResponseMeta rm){
		try{
			Interpreter ite = new Interpreter();
			String f = rm.getFormula();
			for(ResponseItem item : res.getItems()){
				if(f.contains(item.getName())){
					f = f.replaceAll(item.getName(), item.getValue().toString());
				}
			}
			System.out.println(f+"="+ite.eval(f));
			res.add(rm.getName(), ite.eval(f), rm.getUnit());
		}catch(Throwable e){
			logger.error(e.getMessage());
		}
	}
	
	public static void calFormula(List<ResponseItem> items,ResponseMeta rm){
		for(ResponseItem item : items){
			if(rm.getName().equals(item.getName()) && item.getValue()!=null){
				try{
					Interpreter ite = new Interpreter();
		            item.setValue(ite.eval(rm.getFormula().replaceAll("val", item.getValue().toString())));
				}catch(Throwable e){
					logger.error(e.getMessage());
				}
			}
		}
	}
	
	public static void main(String[] args)throws Exception{
		Interpreter ite = new Interpreter();
        String exp = "(val+5)/3*6+2".replaceAll("val", "5");
        System.out.println(ite.eval(exp));
	}

}
